SQL FOREIGN KEY Constraint
SQL FOREIGN KEY Constraint:
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table
The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.
SQL FOREIGN KEY on CREATE TABLE:
CREATE TABLE Orders (OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
SQL FOREIGN KEY on ALTER TABLE:
ALTER TABLE Orders ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
DROP a FOREIGN KEY Constraint:
ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;